/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.edu.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.edu.entity.EduTwoOrganization;
import com.jeesite.modules.edu.service.EduTwoOrganizationService;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.utils.UserUtils;

/**
 * edu_two_organizationController
 * @author 赵俊飞
 * @version 2019-03-13
 */
@Controller
@RequestMapping(value = "${adminPath}/edu/eduTwoOrganization")
public class EduTwoOrganizationController extends BaseController {

	@Autowired
	private EduTwoOrganizationService eduTwoOrganizationService;
	@Autowired
	private EmployeeService employeeService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public EduTwoOrganization get(String dictCode, boolean isNewRecord) {
		return eduTwoOrganizationService.get(dictCode, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("edu:eduTwoOrganization:view")
	@RequestMapping(value = {"list", ""})
	public String list(EduTwoOrganization eduTwoOrganization, Model model) {
		model.addAttribute("eduTwoOrganization", eduTwoOrganization);
		return "modules/edu/eduTwoOrganizationList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("edu:eduTwoOrganization:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<EduTwoOrganization> listData(EduTwoOrganization eduTwoOrganization,HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isBlank(eduTwoOrganization.getParentCode())) {
			eduTwoOrganization.setParentCode(EduTwoOrganization.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getDictLabel())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getDictValue())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getDictType())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getIsSys())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getDescription())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getCssStyle())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getCssClass())){
			eduTwoOrganization.setParentCode(null);
		}
		if (StringUtils.isNotBlank(eduTwoOrganization.getRemarks())){
			eduTwoOrganization.setParentCode(null);
		}
		User user = UserUtils.getUser();
		if(!org.springframework.util.StringUtils.isEmpty(user)) {
			Employee employee = employeeService.get(user.getUserCode());
			if(!org.springframework.util.StringUtils.isEmpty(employee)) {
				Office office = employee.getOffice();
				if(!org.springframework.util.StringUtils.isEmpty(office)) {
					eduTwoOrganization.setDictType(office.getOfficeCode());
				}
			}
		}
		eduTwoOrganization.setPage(new Page<>(request, response));
		Page<EduTwoOrganization> page = eduTwoOrganizationService.findPage(eduTwoOrganization);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("edu:eduTwoOrganization:view")
	@RequestMapping(value = "form")
	public String form(EduTwoOrganization eduTwoOrganization, Model model) {
		// 创建并初始化下一个节点信息
		eduTwoOrganization = createNextNode(eduTwoOrganization);
		model.addAttribute("eduTwoOrganization", eduTwoOrganization);
		return "modules/edu/eduTwoOrganizationForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("edu:eduTwoOrganization:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public EduTwoOrganization createNextNode(EduTwoOrganization eduTwoOrganization) {
		if (StringUtils.isNotBlank(eduTwoOrganization.getParentCode())){
			eduTwoOrganization.setParent(eduTwoOrganizationService.get(eduTwoOrganization.getParentCode()));
		}
		if (eduTwoOrganization.getIsNewRecord()) {
			EduTwoOrganization where = new EduTwoOrganization();
			where.setParentCode(eduTwoOrganization.getParentCode());
			EduTwoOrganization last = eduTwoOrganizationService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				eduTwoOrganization.setTreeSort(last.getTreeSort() + 30);
				eduTwoOrganization.setDictCode(IdGen.nextCode(last.getDictCode()));
			}else if (eduTwoOrganization.getParent() != null){
				eduTwoOrganization.setDictCode(eduTwoOrganization.getParent().getDictCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (eduTwoOrganization.getTreeSort() == null){
			eduTwoOrganization.setTreeSort(EduTwoOrganization.DEFAULT_TREE_SORT);
		}
		return eduTwoOrganization;
	}

	/**
	 * 保存edu_two_organization
	 */
	/**
	 * @param eduTwoOrganization
	 * @return
	 */
	@RequiresPermissions("edu:eduTwoOrganization:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated EduTwoOrganization eduTwoOrganization) {
		User user = UserUtils.getUser();
		if(!org.springframework.util.StringUtils.isEmpty(user)) {
			if(!user.isAdmin()) {
				Employee employee = employeeService.get(user.getUserCode());
				if(!org.springframework.util.StringUtils.isEmpty(employee)) {
					Office office = employee.getOffice();
					if(!org.springframework.util.StringUtils.isEmpty(office)) {
						eduTwoOrganization.setDictType(office.getOfficeCode());
						eduTwoOrganization.setDictValue(office.getOfficeName());
					}
				}
				
			}
		}
		eduTwoOrganizationService.save(eduTwoOrganization);
		return renderResult(Global.TRUE, text("保存edu_two_organization成功！"));
	}
	
	/**
	 * 删除edu_two_organization
	 */
	@RequiresPermissions("edu:eduTwoOrganization:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(EduTwoOrganization eduTwoOrganization) {
		eduTwoOrganizationService.delete(eduTwoOrganization);
		return renderResult(Global.TRUE, text("删除edu_two_organization成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		EduTwoOrganization twoOrganization = new EduTwoOrganization();
		User user = UserUtils.getUser();
		if(!user.isAdmin()) {
			List<Role> roles = user.getRoleList();
			logger.info("roles:{}",roles.size());
			for(Role role : roles) {
				if(role.getRoleCode().equals("teacher")||role.getRoleCode().equals("admin")) {
					Employee employee = employeeService.get(user.getUserCode());
					Office office = employee.getOffice();
					if(!org.springframework.util.StringUtils.isEmpty(office)) {
						twoOrganization.setDictType(office.getOfficeCode());
					}
				}
			}
			
		}
		List<EduTwoOrganization> list = eduTwoOrganizationService.findList(twoOrganization);
		//设置默认队列
		//list.add(0, eduTwoOrganizationService.get("99999999"));
		for (int i=0; i<list.size(); i++){
			EduTwoOrganization e = list.get(i);
			// 过滤非正常的数据
			if (!EduTwoOrganization.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getDictCode(), e.getDictLabel()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("edu:eduTwoOrganization:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(EduTwoOrganization eduTwoOrganization){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		eduTwoOrganizationService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}